package com.hbnu.system.controller;

import com.hbnu.system.core.base.Rest;
import com.hbnu.system.model.entity.Paper;
import com.hbnu.system.model.entity.Paperauthor;
import com.hbnu.system.model.entity.ProjectSourceUnit;
import com.hbnu.system.service.IPaperService;
import com.hbnu.system.service.IPaperauthorService;
import com.hbnu.system.service.IProjectSourceUnitService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 来源单位/企业所在国家、省份、城市信息表 前端控制器
 * </p>
 *
 * @author jxl
 * @since 2025-07-12
 */
@Api(tags = "来源单位/企业所在国家、省份、城市信息表模块")
@RestController
@RequestMapping("/project-source-unit")
public class ProjectSourceUnitController {

    @Autowired
    private IProjectSourceUnitService projectSourceUnitService;

    @ApiOperation("获取所有来源企业分类选项")
    @GetMapping("/getAll")
    public Rest<List<Map<String, Object>>> getAll() {
        List<ProjectSourceUnit> list = projectSourceUnitService.list();
        List<Map<String, Object>> tree = convertToTree(list);
        return Rest.success(tree);
    }

    private List<Map<String, Object>> convertToTree(List<ProjectSourceUnit> data) {
        if (data == null || data.isEmpty()) {
            return new ArrayList<>();
        }

        // 用于存储所有节点的映射，键为节点唯一标识
        Map<String, Map<String, Object>> nodeMap = new LinkedHashMap<>();
        // 存储所有国家节点
        Map<String, Map<String, Object>> countryNodes = new LinkedHashMap<>();
        // 存储所有省份节点
        Map<String, Map<String, Object>> provinceNodes = new LinkedHashMap<>();

        for (ProjectSourceUnit item : data) {
            if (item == null) {
                continue;
            }

            // 创建国家节点
            Integer countryId = item.getCountryId();
            String countryLevel = item.getCountryLevel();
            if (countryId != null && countryLevel != null) {
                String countryKey = "country_" + countryId;
                if (!nodeMap.containsKey(countryKey)) {
                    Map<String, Object> countryNode = new LinkedHashMap<>();
                    countryNode.put("value", countryId);
                    countryNode.put("label", countryLevel);
                    countryNode.put("children", new ArrayList<>());
                    nodeMap.put(countryKey, countryNode);
                    countryNodes.put(countryKey, countryNode);
                }
            }

            // 创建省份节点（如果存在）
            Integer provinceId = item.getProvinceId();
            String provinceName = item.getProvinceName();
            if (provinceId != null && provinceName != null && countryId != null) {
                String provinceKey = "province_" + provinceId;
                Map<String, Object> provinceNode;
                if (!nodeMap.containsKey(provinceKey)) {
                    provinceNode = new LinkedHashMap<>();
                    provinceNode.put("value", provinceId);
                    provinceNode.put("label", provinceName);
                    provinceNode.put("children", new ArrayList<>());
                    nodeMap.put(provinceKey, provinceNode);
                    provinceNodes.put(provinceKey, provinceNode);
                } else {
                    provinceNode = nodeMap.get(provinceKey);
                }

                // 将省份节点添加到对应的国家节点下
                String countryKey = "country_" + countryId;
                if (nodeMap.containsKey(countryKey)) {
                    boolean exists = false;
                    List<Map<String, Object>> countryChildren = (List<Map<String, Object>>) nodeMap.get(countryKey).get("children");
                    for (Map<String, Object> child : countryChildren) {
                        if (child.get("value").equals(provinceId)) {
                            exists = true;
                            break;
                        }
                    }
                    if (!exists) {
                        countryChildren.add(provinceNode);
                    }
                }
            }

            // 创建城市节点（如果存在）
            Integer cityId = item.getCityId();
            String cityName = item.getCityName();
            if (cityId != null && cityName != null && countryId != null) {
                String cityKey = "city_" + cityId;
                Map<String, Object> cityNode;
                if (!nodeMap.containsKey(cityKey)) {
                    cityNode = new LinkedHashMap<>();
                    cityNode.put("value", cityId);
                    cityNode.put("label", cityName);
                    cityNode.put("id", item.getId());
                    nodeMap.put(cityKey, cityNode);
                } else {
                    cityNode = nodeMap.get(cityKey);
                }

                // 将城市节点添加到对应的省份或国家节点下
                if (provinceId != null) {
                    String provinceKey = "province_" + provinceId;
                    if (nodeMap.containsKey(provinceKey)) {
                        boolean exists = false;
                        List<Map<String, Object>> provinceChildren = (List<Map<String, Object>>) nodeMap.get(provinceKey).get("children");
                        for (Map<String, Object> child : provinceChildren) {
                            if (child.get("value").equals(cityId)) {
                                exists = true;
                                break;
                            }
                        }
                        if (!exists) {
                            provinceChildren.add(cityNode);
                        }
                    }
                } else {
                    // 如果没有省份信息，直接添加到国家节点下
                    String countryKey = "country_" + countryId;
                    if (nodeMap.containsKey(countryKey)) {
                        boolean exists = false;
                        List<Map<String, Object>> countryChildren = (List<Map<String, Object>>) nodeMap.get(countryKey).get("children");
                        for (Map<String, Object> child : countryChildren) {
                            if (child.get("value").equals(cityId)) {
                                exists = true;
                                break;
                            }
                        }
                        if (!exists) {
                            countryChildren.add(cityNode);
                        }
                    }
                }
            }
        }

        // 返回所有国家节点作为顶级节点
        return new ArrayList<>(countryNodes.values());
    }


    @Autowired
    private IPaperauthorService paperauthorService;
    @Autowired
    private IPaperService paperService;

    @ApiOperation("批量更新所有论文的作者字段格式")
    @GetMapping("/test")
    public Rest<String> test() {
        // 拿到所有的 paper 的 id 集合
        List<Paper> papers = paperService.list();
        if (papers == null || papers.isEmpty()) {
            return Rest.success("没有需要更新的论文数据");
        }

        List<String> ids = papers.stream()
                .map(Paper::getPaperID)
                .collect(Collectors.toList());

        List<Paper> updateList = new ArrayList<>();

        // 遍历 ids 查询作者信息，并封装到 Paper 对象中
        for (String id : ids) {
            List<Paperauthor> authors = paperauthorService.listAuthor(id);
            String author = Optional.ofNullable(authors)
                    .orElse(Collections.emptyList())
                    .stream()
                    .map(a -> {
                        String name = a.getName();
                        String authorType = a.getAuthortype();
                        // 如果作者类型为空或null，只返回姓名
                        if (authorType == null || authorType.trim().isEmpty()) {
                            return name;
                        }
                        // 否则返回 姓名【作者属性】
                        return name + "【" + authorType + "】";
                    })
                    .collect(Collectors.joining("、"));

            Paper paper = new Paper();
            paper.setPaperID(id);
            paper.setAllAuthorName(author);  // 设置作者字段(格式：姓名【作者属性】、姓名【作者属性】)

            updateList.add(paper);
        }

        // 执行批量更新（默认每批 1000 条）
        if (!updateList.isEmpty()) {
            paperService.updateBatchById(updateList);
        }
        
        return Rest.success("成功更新 " + updateList.size() + " 条论文的作者字段格式");
    }


}
